<?php

namespace app\common\service;

use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;

class TokenService extends BaseService
{
    protected static $key = 'd55d5ddkgkkgiiijys36666d';

    public function createToken($uid, $exp=86400)
    {
        $time = time();
        $payload = array(
            "iss" => request()->host(), //签发人 可以为空
            "aud" => request()->host(), //面向的用户 可以为空
            "iat" => $time, //签发时间
            "nbf" => $time, //生效时间
            "exp" => $time + $exp, //过期时间
            "uid" => $uid
        );
        $jwt = JWT::encode($payload, self::$key, 'HS256');
        return $jwt;
    }

    public function checkToken($token)
    {
        if( $token == '' ) {
            retError('Token is empty', 401);
        }
        try {
            $payload = JWT::decode($token, new Key(self::$key, 'HS256'));
            if( !$payload ) {
                retError('Token error', 401);
            }
            $payload = (array) $payload;
            //签发时间大于当前服务器时间验证失败
            if (isset($payload['iat']) && $payload['iat'] > time())
                retError('Token error', 401);
            if (isset($payload['exp']) && $payload['exp'] < time())
                retError('Token', 401);
            if (isset($payload['nbf']) && $payload['nbf'] > time())
                retError('Token error', 401);
            return $payload;
        } catch (SignatureInvalidException $e) { //签名不正确
            retError($e->getMessage(), 401);
        } catch ( ExpiredException $e ) { //token过期
            retError($e->getMessage(), 401);
        } catch ( \Exception $e ) { //其他错误
            retError($e->getMessage(), 401);
        } catch ( \Throwable $e) {
            retError($e->getMessage(), 401);
        }
    }
}